from ferris import BasicModel
from google.appengine.ext import ndb
from app.models import util
from app.models.issue import Issue


class Publication(BasicModel):
    """
    Models publications like printed or digital magazines. Publications can
    have a certain publication frequency. A link to its homepage can also be
    stored.
    """
    name = ndb.StringProperty(required=True)
    name_sort = ndb.ComputedProperty(lambda self:
                                     util.homogenize_name(self.name))
    publication_frequency = ndb.KeyProperty(kind="PublicationFrequency")
    homepage = ndb.StringProperty()
    search_terms = ndb.ComputedProperty(lambda self:
                                        util.create_search_terms(self.name),
                                        repeated=True)

    def homepage_short(self):
        """
        Returns a shortened homepage URL.
        """
        return util.shorten_url(self.homepage) if self.homepage else None

    @classmethod
    def list_query(cls, query=None):
        """
        Queries all publications with an optional query string, ordered
        alphabetically.
        """
        if query:
            search_args = util.prepare_search_args(query)
            results = cls.query(cls.search_terms.IN(search_args))
        else:
            results = cls.query()

        return results.order(cls.name_sort, cls.key)

    def all_issues(self):
        """
        List all issues of a publication.
        """
        return Issue.query(Issue.publication == self.key).order(
            -Issue.publication_day)
